const Koa =require('koa');
const koaviews = require('koa-views');
const koafavicon = require('koa-favicon');
const koastatic=require('koa-static');
const bodyParser = require('koa-bodyparser');
const json = require('koa-json');
const onerror = require('koa-onerror');
const logger = require('koa-logger');

const router = require('./middleware/router');
const renderJson = require('./middleware/renderJson');
const render = require('./middleware/render');
const cache = require('./middleware/cache');
const static = require('./middleware/static');
const clogger = require('./middleware/loggers');

const app=new Koa();

/**
 * logs
*/
app.use(logger())
app.use(clogger())

/**
 * 一个为koa的请求体，基于co-body。支持json、表单和文本类型主体。
*/
app.use(bodyParser());

/**
 * 返回结果JSON spaces 
*/
app.use(json());

/**
 * favicon.ico
*/
app.use(koafavicon(__dirname + '/favicon.ico'));

/**
 * static cache
*/
// app.use(async (ctx, next) => {
//     ctx.set('Cache-Control', "public,max-age=60000");
//     await next();
// });
app.use(cache({
    public:true,
    maxAge:31536000
}))

app.use(static())

/**
 * static directory:assets 3rd
*/
app.use(koastatic(__dirname + '/assets'));
app.use(koastatic(__dirname + '/3rd'))

/**
 * template:nunjucks
*/
app.use(koaviews('views', {
    root: __dirname+'/views',
    map: {
      html: 'nunjucks'
    }
}));


/**
 * render JSON
 */
app.use(renderJson());
app.use(render());

/**
 * routes
*/
app.use(router());



onerror(app);

// error-handling  “error” 事件侦听器：
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
});

app.listen(3001);

console.log('[demo] start-quick is starting at port 3001')